<template>
  <div class="search-page">
    <div class="container">
      <!-- 搜索头部 -->
      <div class="search-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <div class="search-input-wrapper">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索服务、商家..."
            clearable
            @keyup.enter="handleSearch"
            @clear="handleClear"
          >
            <template #suffix>
              <el-button @click="handleSearch" :icon="Search" link />
            </template>
          </el-input>
        </div>
      </div>

      <!-- 搜索历史 -->
      <el-card class="search-history-card" v-if="!hasSearched && searchHistory.length > 0">
        <div class="history-header">
          <h3>搜索历史</h3>
          <el-button link @click="clearHistory">清空</el-button>
        </div>
        <div class="history-tags">
          <el-tag
            v-for="(item, index) in searchHistory"
            :key="index"
            @click="searchHistoryItem(item)"
            class="history-tag"
          >
            {{ item }}
          </el-tag>
        </div>
      </el-card>

      <!-- 热门搜索 -->
      <el-card class="hot-search-card" v-if="!hasSearched">
        <h3>热门搜索</h3>
        <div class="hot-tags">
          <el-tag
            v-for="(item, index) in hotSearches"
            :key="index"
            :type="index < 3 ? 'danger' : 'info'"
            @click="searchHistoryItem(item)"
            class="hot-tag"
          >
            {{ item }}
          </el-tag>
        </div>
      </el-card>

      <!-- 筛选条件 -->
      <el-card class="filter-card" v-if="hasSearched">
        <div class="filter-header">
          <span>筛选条件</span>
          <el-button link @click="resetFilters">重置</el-button>
        </div>
        <div class="filter-content">
          <div class="filter-row">
            <span class="filter-label">分类：</span>
            <div class="filter-options">
              <el-tag
                v-for="category in categories"
                :key="category.id"
                :type="selectedCategory === category.id ? 'primary' : 'info'"
                @click="selectCategory(category.id)"
                class="filter-tag"
              >
                {{ category.name }}
              </el-tag>
            </div>
          </div>
          <div class="filter-row">
            <span class="filter-label">价格：</span>
            <div class="filter-options">
              <el-tag
                v-for="price in priceRanges"
                :key="price.value"
                :type="selectedPriceRange === price.value ? 'primary' : 'info'"
                @click="selectPriceRange(price.value)"
                class="filter-tag"
              >
                {{ price.label }}
              </el-tag>
            </div>
          </div>
          <div class="filter-row">
            <span class="filter-label">排序：</span>
            <div class="filter-options">
              <el-tag
                v-for="sort in sortOptions"
                :key="sort.value"
                :type="selectedSort === sort.value ? 'primary' : 'info'"
                @click="selectSort(sort.value)"
                class="filter-tag"
              >
                {{ sort.label }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 搜索结果 -->
      <div class="search-results" v-if="hasSearched">
        <div class="results-header">
          <span>搜索结果 ({{ totalResults }})</span>
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部" name="all" />
            <el-tab-pane label="商家" name="merchants" />
            <el-tab-pane label="服务" name="services" />
          </el-tabs>
        </div>

        <!-- 结果列表 -->
        <div class="results-list" v-loading="searchLoading">
          <!-- 无结果状态 -->
          <div v-if="searchResults.length === 0 && !searchLoading" class="no-results">
            <el-empty description="没有找到相关结果">
              <el-button type="primary" @click="adjustSearch">调整搜索条件</el-button>
            </el-empty>
          </div>

          <!-- 商家结果 -->
          <div
            v-for="item in searchResults"
            :key="`${item.type}-${item.id}`"
            class="result-item"
            @click="handleResultClick(item)"
          >
            <div class="result-image">
              <el-image
                :src="item.image || '/default-image.jpg'"
                fit="cover"
                :lazy="true"
              />
              <div class="result-type-badge">
                <el-tag :type="item.type === 'merchant' ? 'primary' : 'success'" size="small">
                  {{ item.type === 'merchant' ? '商家' : '服务' }}
                </el-tag>
              </div>
            </div>

            <div class="result-content">
              <div class="result-header">
                <h3 class="result-title">{{ item.title }}</h3>
                <div class="result-rating" v-if="item.rating">
                  <el-rate
                    :model-value="item.rating"
                    disabled
                    size="small"
                    show-score
                  />
                </div>
              </div>

              <p class="result-description">{{ item.description }}</p>

              <div class="result-meta">
                <div class="meta-info">
                  <span class="price" v-if="item.price">
                    ¥{{ item.price }}起
                  </span>
                  <span class="location" v-if="item.location">
                    <el-icon><Location /></el-icon>
                    {{ item.location }}
                  </span>
                  <span class="category" v-if="item.category">
                    {{ item.category }}
                  </span>
                </div>
                <div class="result-actions">
                  <el-button size="small" type="primary">
                    {{ item.type === 'merchant' ? '查看商家' : '立即预约' }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore && !searchLoading">
          <el-button @click="loadMore" :loading="loadingMore">
            加载更多
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Search, Location } from '@element-plus/icons-vue'
import { searchApi } from '@/services/api'

const route = useRoute()
const router = useRouter()

// 数据定义
const searchKeyword = ref('')
const hasSearched = ref(false)
const searchLoading = ref(false)
const loadingMore = ref(false)
const searchResults = ref([])
const totalResults = ref(0)
const hasMore = ref(false)
const page = ref(1)
const pageSize = ref(10)
const activeTab = ref('all')

// 筛选条件
const selectedCategory = ref('')
const selectedPriceRange = ref('')
const selectedSort = ref('default')

// 搜索历史和热门搜索
const searchHistory = ref([])
const hotSearches = ref([
  '家政服务', '洗车服务', '家电维修', '管道疏通', '搬家服务',
  '保洁服务', '空调清洗', '手机维修', '电脑维修', '美甲服务'
])

// 筛选选项
const categories = ref([
  { id: '', name: '全部' },
  { id: 'housekeeping', name: '家政服务' },
  { id: 'repair', name: '维修服务' },
  { id: 'cleaning', name: '清洁服务' },
  { id: 'beauty', name: '美容美护' },
  { id: 'pet', name: '宠物服务' }
])

const priceRanges = ref([
  { value: '', label: '不限' },
  { value: '0-50', label: '50元以下' },
  { value: '50-100', label: '50-100元' },
  { value: '100-200', label: '100-200元' },
  { value: '200+', label: '200元以上' }
])

const sortOptions = ref([
  { value: 'default', label: '默认排序' },
  { value: 'price_asc', label: '价格从低到高' },
  { value: 'price_desc', label: '价格从高到低' },
  { value: 'rating', label: '评分优先' },
  { value: 'distance', label: '距离优先' }
])

// 生命周期
onMounted(() => {
  loadSearchHistory()
  
  // 如果URL中有搜索关键词，自动搜索
  if (route.query.q) {
    searchKeyword.value = route.query.q
    handleSearch()
  }
})

// 监听筛选条件变化
watch([selectedCategory, selectedPriceRange, selectedSort], () => {
  if (hasSearched.value) {
    handleSearch()
  }
})

// 方法定义
const loadSearchHistory = () => {
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history).slice(0, 8) // 最多显示8个
  }
}

const saveSearchHistory = (keyword) => {
  if (!keyword.trim()) return
  
  let history = searchHistory.value.slice()
  
  // 移除重复项
  const index = history.indexOf(keyword)
  if (index > -1) {
    history.splice(index, 1)
  }
  
  // 添加到开头
  history.unshift(keyword)
  
  // 最多保存20个
  history = history.slice(0, 20)
  
  searchHistory.value = history.slice(0, 8)
  localStorage.setItem('searchHistory', JSON.stringify(history))
}

const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  hasSearched.value = true
  page.value = 1
  
  saveSearchHistory(searchKeyword.value)
  
  // 更新URL
  router.replace({
    query: { ...route.query, q: searchKeyword.value }
  })

  await performSearch()
}

const performSearch = async () => {
  try {
    searchLoading.value = true
    
    const params = {
      keyword: searchKeyword.value,
      type: activeTab.value === 'all' ? undefined : activeTab.value,
      category: selectedCategory.value || undefined,
      priceRange: selectedPriceRange.value || undefined,
      sort: selectedSort.value,
      page: page.value,
      pageSize: pageSize.value
    }

    const response = await searchApi.search(params)
    const { data, total } = response.data
    
    if (page.value === 1) {
      searchResults.value = data
    } else {
      searchResults.value.push(...data)
    }
    
    totalResults.value = total
    hasMore.value = searchResults.value.length < total
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请重试')
  } finally {
    searchLoading.value = false
    loadingMore.value = false
  }
}

const handleClear = () => {
  searchKeyword.value = ''
  hasSearched.value = false
  searchResults.value = []
  resetFilters()
}

const searchHistoryItem = (keyword) => {
  searchKeyword.value = keyword
  handleSearch()
}

const handleTabChange = (tab) => {
  activeTab.value = tab
  page.value = 1
  performSearch()
}

const selectCategory = (categoryId) => {
  selectedCategory.value = selectedCategory.value === categoryId ? '' : categoryId
}

const selectPriceRange = (range) => {
  selectedPriceRange.value = selectedPriceRange.value === range ? '' : range
}

const selectSort = (sort) => {
  selectedSort.value = sort
}

const resetFilters = () => {
  selectedCategory.value = ''
  selectedPriceRange.value = ''
  selectedSort.value = 'default'
}

const adjustSearch = () => {
  resetFilters()
  hasSearched.value = false
}

const loadMore = () => {
  page.value++
  loadingMore.value = true
  performSearch()
}

const handleResultClick = (item) => {
  if (item.type === 'merchant') {
    router.push(`/merchants/${item.id}`)
  } else {
    router.push(`/services/${item.id}`)
  }
}

const handleBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;

  .search-input-wrapper {
    flex: 1;
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-history-card {
  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .history-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .history-tag {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}

.hot-search-card {
  h3 {
    margin: 0 0 16px 0;
    font-size: 16px;
    font-weight: 600;
  }

  .hot-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .hot-tag {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}

.filter-card {
  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    font-weight: 600;
  }

  .filter-content {
    .filter-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .filter-label {
        min-width: 50px;
        color: #666;
        font-size: 14px;
      }

      .filter-options {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .filter-tag {
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-1px);
          }
        }
      }
    }
  }
}

.search-results {
  .results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    :deep(.el-tabs) {
      .el-tabs__header {
        margin: 0;
      }
    }
  }

  .results-list {
    .no-results {
      padding: 60px 20px;
      text-align: center;
    }

    .result-item {
      display: flex;
      background: white;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        transform: translateY(-1px);
      }

      .result-image {
        width: 120px;
        height: 120px;
        border-radius: 8px;
        overflow: hidden;
        margin-right: 16px;
        flex-shrink: 0;
        position: relative;

        .el-image {
          width: 100%;
          height: 100%;
        }

        .result-type-badge {
          position: absolute;
          top: 8px;
          left: 8px;
        }
      }

      .result-content {
        flex: 1;
        display: flex;
        flex-direction: column;

        .result-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 8px;

          .result-title {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: #333;
            line-height: 1.4;
          }

          .result-rating {
            margin-left: 12px;
            flex-shrink: 0;
          }
        }

        .result-description {
          margin: 0 0 auto 0;
          color: #666;
          font-size: 14px;
          line-height: 1.5;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .result-meta {
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          margin-top: 12px;

          .meta-info {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: center;

            .price {
              color: #e6a23c;
              font-weight: 600;
              font-size: 16px;
            }

            .location,
            .category {
              display: flex;
              align-items: center;
              color: #666;
              font-size: 12px;

              .el-icon {
                margin-right: 4px;
              }
            }
          }

          .result-actions {
            flex-shrink: 0;
            margin-left: 12px;
          }
        }
      }
    }
  }

  .load-more {
    text-align: center;
    margin-top: 20px;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .filter-content {
    .filter-row {
      flex-direction: column;
      align-items: stretch;
      gap: 8px;

      .filter-label {
        min-width: auto;
      }
    }
  }

  .results-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .result-item {
    flex-direction: column;

    .result-image {
      width: 100%;
      height: 200px;
      margin-right: 0;
      margin-bottom: 12px;
    }

    .result-content {
      .result-meta {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;

        .result-actions {
          margin-left: 0;
          align-self: flex-start;
        }
      }
    }
  }
}
</style> 